package org.yray.bytebuddy;

import net.bytebuddy.ByteBuddy;
import net.bytebuddy.agent.ByteBuddyAgent;
import net.bytebuddy.dynamic.loading.ClassReloadingStrategy;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.matcher.ElementMatchers;

import java.lang.instrument.Instrumentation;

public class MainAgent2 {
    public static void agentmain(String agentArgs, Instrumentation ins) throws ClassNotFoundException {
        System.out.println("MainAgent:" + agentArgs);

        ByteBuddyAgent.install();
        Class<?> dynamicType = new ByteBuddy()
                // 指定父类
                .subclass(Class.forName("org.yray.javaagent.exec.RetListCls"))
                // 根据名称来匹配需要拦截的方法
                .method(ElementMatchers.named("list"))
                // 拦截方法调用，返回固定值
                .intercept(MethodDelegation.to(MyServiceInterceptor.class))
                // 产生字节码
                .make()
                // 加载类
                .load(Class.forName("org.yray.javaagent.exec.RetListCls").getClass().getClassLoader())
                // 获得Class对象
                .getLoaded();
        try {
            new ByteBuddy()
                    .redefine(dynamicType)
                    .name("org.yray.javaagent.exec.RetListCls")
                    .make()
                    .load(Class.forName("org.yray.javaagent.exec.RetListCls").getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
